import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getWalletInfo, rechargeWallet } from '../../services/payment';
import useAuthStore from '../../store/auth';
import usePaymentStore from '../../store/payment';

const Wallet: React.FC = () => {
  const [walletData, setWalletData] = useState<any>(null);
  const [rechargeAmount, setRechargeAmount] = useState<number>(10);
  const [loading, setLoading] = useState(true);
  const [rechargeLoading, setRechargeLoading] = useState(false);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const pendingOrder = usePaymentStore(state => state.pendingOrder);
  const setWallet = usePaymentStore(state => state.setWallet);
  const clearPendingOrder = usePaymentStore(state => state.clearPendingOrder);
  
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
      return;
    }
    
    fetchWalletInfo();
  }, [isAuthenticated]);
  
  const fetchWalletInfo = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await getWalletInfo();
      
      if (response.code === 200) {
        setWalletData(response.data);
        setWallet({
          balance: response.data.balance,
          totalRecharge: response.data.totalRecharge,
          totalConsume: response.data.totalConsume
        });
      } else {
        setError(response.message || '获取钱包信息失败');
      }
    } catch (err: any) {
      setError(err.message || '获取钱包信息失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  const handleRecharge = async () => {
    if (rechargeAmount <= 0) {
      setError('充值金额必须大于0');
      return;
    }
    
    try {
      setRechargeLoading(true);
      setError('');
      
      // 调用充值API
      const response = await rechargeWallet({
        amount: rechargeAmount,
        paymentType: 'alipay' // 模拟支付方式
      });
      
      if (response.code === 200) {
        // 充值成功，更新钱包信息
        setWalletData(prev => ({
          ...prev,
          balance: response.data.balance,
          totalRecharge: response.data.totalRecharge
        }));
        
        setWallet({
          balance: response.data.balance,
          totalRecharge: response.data.totalRecharge,
          totalConsume: walletData.totalConsume
        });
        
        // 如果有待支付订单，跳转到相应页面
        if (pendingOrder.productType) {
          const path = getPathByProductType(pendingOrder.productType, pendingOrder.productId);
          clearPendingOrder();
          if (path) {
            navigate(path);
          }
        }
        
        // 显示成功消息
        alert('充值成功！');
      } else {
        setError(response.message || '充值失败');
      }
    } catch (err: any) {
      setError(err.message || '充值失败，请稍后再试');
    } finally {
      setRechargeLoading(false);
    }
  };
  
  // 根据产品类型获取跳转路径
  const getPathByProductType = (productType: string, productId: string | null) => {
    switch (productType) {
      case 'bazi_detail':
        return `/bazi/${productId}`;
      case 'character_detail':
        return `/character`;
      case 'fengshui_detail':
        return `/fengshui/${productId}`;
      case 'name_analysis_detail':
        return `/tools/name`;
      case 'fortune_detail':
        return `/fortune/daily/${productId}`;
      default:
        return '';
    }
  };
  
  // 快速充值金额选项
  const quickAmounts = [10, 20, 50, 100];
  
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto bg-white rounded-xl shadow-md overflow-hidden">
        <div className="p-6">
          <h2 className="text-2xl font-bold text-gray-900 text-center mb-6">我的钱包</h2>
          
          {error && (
            <div className="text-red-500 text-sm text-center mb-4">
              {error}
            </div>
          )}
          
          {/* 钱包信息 */}
          <div className="bg-gradient-to-r from-indigo-500 to-purple-600 rounded-lg p-6 text-white mb-8">
            <div className="text-center mb-4">
              <h3 className="text-lg font-medium">账户余额</h3>
              <div className="text-4xl font-bold mt-2">¥ {walletData?.balance.toFixed(2)}</div>
            </div>
            
            <div className="grid grid-cols-2 gap-4 text-center">
              <div>
                <h4 className="text-sm opacity-80">累计充值</h4>
                <div className="text-xl font-medium mt-1">¥ {walletData?.totalRecharge.toFixed(2)}</div>
              </div>
              <div>
                <h4 className="text-sm opacity-80">累计消费</h4>
                <div className="text-xl font-medium mt-1">¥ {walletData?.totalConsume.toFixed(2)}</div>
              </div>
            </div>
            
            {walletData?.isVip && (
              <div className="mt-4 bg-yellow-400 bg-opacity-20 rounded-md p-2 text-center">
                <span className="text-yellow-200 font-medium">VIP会员</span>
                <span className="text-yellow-100 text-sm ml-2">到期时间: {walletData.vipExpireTime}</span>
              </div>
            )}
          </div>
          
          {/* 充值区域 */}
          <div className="mb-8">
            <h3 className="text-lg font-medium text-gray-900 mb-4">账户充值</h3>
            
            {/* 快速充值金额 */}
            <div className="grid grid-cols-4 gap-3 mb-4">
              {quickAmounts.map(amount => (
                <button
                  key={amount}
                  onClick={() => setRechargeAmount(amount)}
                  className={`py-2 px-4 rounded-md text-center ${
                    rechargeAmount === amount
                      ? 'bg-indigo-100 text-indigo-700 border-2 border-indigo-500'
                      : 'bg-gray-100 text-gray-700 border border-gray-300'
                  }`}
                >
                  ¥{amount}
                </button>
              ))}
            </div>
            
            {/* 自定义充值金额 */}
            <div className="mb-4">
              <label htmlFor="customAmount" className="block text-sm font-medium text-gray-700 mb-1">
                自定义金额
              </label>
              <input
                type="number"
                id="customAmount"
                min="0.1"
                step="0.1"
                className="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={rechargeAmount}
                onChange={(e) => setRechargeAmount(parseFloat(e.target.value) || 0)}
              />
            </div>
            
            {/* 充值按钮 */}
            <button
              onClick={handleRecharge}
              disabled={rechargeLoading}
              className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${rechargeLoading ? 'opacity-70 cursor-not-allowed' : ''}`}
            >
              {rechargeLoading ? '处理中...' : '立即充值'}
            </button>
            
            <div className="mt-2 text-xs text-gray-500 text-center">
              注：充值为模拟操作，实际不会产生费用
            </div>
          </div>
          
          {/* 待支付订单提示 */}
          {pendingOrder.productType && (
            <div className="bg-yellow-50 border border-yellow-200 rounded-md p-4 mb-6">
              <div className="flex">
                <div className="flex-shrink-0">
                  <svg className="h-5 w-5 text-yellow-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                    <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                  </svg>
                </div>
                <div className="ml-3">
                  <h3 className="text-sm font-medium text-yellow-800">您有待支付的订单</h3>
                  <div className="mt-2 text-sm text-yellow-700">
                    <p>充值成功后将自动为您完成支付并跳转到相应页面</p>
                  </div>
                </div>
              </div>
            </div>
          )}
          
          {/* 操作按钮 */}
          <div className="flex justify-center space-x-4">
            <button
              onClick={() => navigate('/orders')}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              查看订单
            </button>
            <button
              onClick={() => navigate('/vip')}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              开通VIP
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Wallet;
